<template>
  <div style="width: 90%; margin-left: 5%">
    <el-form ref="editquestion" :model="form" label-width="10%" :rules="rules">
      <el-row>
        <el-col :span="10">
          <el-form-item label="课程" label-width="24%" prop="fkCourseName">
            <el-select
              v-model="form.fkCourseName"
              :disabled="isDisable"
              filterable
              placeholder="请选择课程"
            >
              <el-option v-for="item in courses" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="类型" label-width="46%" prop="type">
            <el-select
              v-model="form.type"
              placeholder="请选择"
              :disabled="isDisable"
              style="width: 120px"
              @change="typeChange"
            >
              <el-option
                v-for="item in types"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分数" label-width="35%" prop="score"
            ><el-input
              type="number"
              v-model="form.score"
              :readonly="isDisable"
              style="width: 128px"
            ></el-input
          ></el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="23">
          <el-form-item label="题目" prop="titleDetail">
            <el-input
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 7 }"
              placeholder="请输入内容"
              clearable
              v-model="form.titleDetail"
              auto-complete="off"
              :readonly="isDisable"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row
        v-if="form.type === 'RADIO_QUESTION' || form.type === 'MULTI_SELECT_QUESTION'"
      >
        <el-col :span="24">
          <el-form-item
            v-for="(selectone, index) in form.selectionList"
            :label="'选项' + (index + 1)"
            :key="index"
            prop="selection"
          >
            <el-input
              type="text"
              style="width: 85%"
              v-model="form.selectionList[index]"
              :readonly="isDisable"
            ></el-input
            ><el-button
              :style="{ display: isDisable === true ? 'none' : '' }"
              style="margin-left: 10px"
              type="warning"
              plain
              @click.prevent="removeSelect(index)"
              >删除</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              :style="{ display: isDisable === true ? 'none' : '' }"
              type="primary"
              plain
              @click="addSelect"
              >新增选项</el-button
            >
            <el-button
              :style="{ display: isDisable === true ? 'none' : '' }"
              type="danger"
              plain
              @click="removeAllSelect"
              >删除所有选项</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item
        v-if="form.type === 'RADIO_QUESTION'"
        label="答案"
        prop="answerlist"
        :key="isReload"
      >
        <el-select
          v-model="form.answer"
          placeholder="请选择答案"
          :disabled="isDisable"
          style="width: 84.8%"
        >
          <el-option
            v-for="(item, index) in form.selectionList"
            :key="index"
            :label="item"
            :value="item"
            :title="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :key="isReload"
        v-else-if="form.type === 'MULTI_SELECT_QUESTION'"
        label="答案"
        prop="answerlist"
      >
        <el-select
          class="answerlist"
          v-model="form.answer"
          multiple
          placeholder="请选择答案"
          :disabled="isDisable"
          style="width: 84.8%"
        >
          <el-option
            v-for="(item, i) in form.selectionList"
            :title="item"
            :key="i"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-else-if="form.type === 'TRUE_FALSE_QUESTION'"
        label="答案"
        prop="answerlist"
      >
        <el-radio v-model="form.answer" label="TRUE_CHOICE">正确</el-radio>
        <el-radio v-model="form.answer" label="FALSE_CHOICE">错误</el-radio>
      </el-form-item>
      <el-row v-else>
        <el-col :span="23">
          <el-form-item label="答案" prop="answer">
            <el-input
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 7 }"
              placeholder="请输入内容"
              clearable
              auto-complete="off"
              :readonly="isDisable"
              v-model="form.answer"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remarks"
        ><el-input
          type="text"
          v-model="form.remarks"
          style="width: 84.8%"
          :readonly="isDisable"
        ></el-input
      ></el-form-item>
      <el-form-item prop="imgList" label="题目图片">
        <el-upload
          class="questionupload"
          action=""
          :multiple="true"
          :limit="3"
          :on-exceed="uploadExceed"
          :on-change="uploadChange"
          :on-remove="uploadRemove"
          :auto-upload="false"
          :file-list="form.imgList"
          list-type="picture"
          accept="image/png,image/jpg,image/jpeg"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传图片，最多为3张，每张不超过2M
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-row>
          <el-col :span="4" :offset="18">
            <el-button
              type="success"
              @click="toEdit"
              icon="el-icon-edit"
              :style="{ display: isDisable === false ? 'none' : '' }"
              >编辑</el-button
            >
            <el-button
              type="primary"
              @click="checkEdit"
              icon="el-icon-lx-forward"
              :style="{ display: isDisable === true ? 'none' : '' }"
              >保存</el-button
            >
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
var _this;
export default {
  props: ["form", "types", "isdisabled", "courses"],
  data() {
    return {
      isDisable: this.isdisabled,
      fileList:
        this.form.imgList === null ? [] : JSON.parse(JSON.stringify(this.form.imgList)),
      isReload: new Date().toString(),
      rules: {
        fkCourseName: [{ required: true, message: "请选择所属课程", trigger: "blur" }],
        type: [{ required: true, message: "请选择题目类型", trigger: "blur" }],
        score: [{ required: true, message: "请输入分数", trigger: "blur" }],
        titleDetail: [{ required: true, message: "请选择题目详情", trigger: "blur" }],
      },
    };
  },
  computed: {},
  watch: {
    isdisabled: function (val, oldval) {
      this.isDisable = this.isdisabled;
    },
    'form.imgList':function(val, oldval){
      this.fileList = this.form.imgList === null ? [] : JSON.parse(JSON.stringify(this.form.imgList))
    },
    "form.type": function (val, oldval) {
      this.$refs.editquestion.clearValidate();
      _this.isReload = new Date().toString();
      if (
        _this.form.type === "RADIO_QUESTION" ||
        _this.form.type === "MULTI_SELECT_QUESTION"
      ) {
        _this.form.selectionList = JSON.parse(JSON.stringify(_this.form.selectionList));
      }
    },
    "form.selectionList": function (val, oldval) {
      if (
        _this.form.type === "RADIO_QUESTION" &&
        _this.form.selectionList.indexOf(_this.form.answer + "") === -1
      ) {
        _this.form.answer = "";
      }
      if (
        _this.form.type === "MULTI_SELECT_QUESTION" &&
        _this.form.selectionList instanceof Array
      ) {
        _this.form.answer = _this.getArrEqual(
          _this.form.selectionList,
          _this.form.answer
        );
      }
    },
  },
  methods: {
    // 状态改变 详情->编辑
    toEdit() {
      this.isDisable = false;
    },
    // 刷新
    typeChange() {
      this.$forceUpdate();
    },
    // 两个数组相同值
    getArrEqual(arr1, arr2) {
      let newArr = [];
      for (let i = 0; i < arr2.length; i++) {
        for (let j = 0; j < arr1.length; j++) {
          if (arr1[j] === arr2[i]) {
            newArr.push(arr1[j]);
          }
        }
      }
      return newArr;
    },
    // 文件数超出
    uploadExceed() {
      this.$message.error("最多只能添加三张照片哟！");
    },
    // 添加文件
    uploadChange(file, list) {
      const isJPG =
        file.raw.type === "image/jpeg" ||
        file.raw.type === "image/png" ||
        file.raw.type === "image/jpeg";
      const isLt2M = file.raw.size / 1024 / 1024 < 2;

      if (!isJPG || !isLt2M) {
        for (let i = 0; i < list.length; i++) {
          if (list[i].uid === file.uid) {
            list.splice(i, 1);
            break;
          }
        }
      }
      if (!isJPG) {
        this.$message.error("请上传类型为png/jpg/jpeg的图片！");
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 2MB!");
      }
      this.fileList = list;
    },
    // 删除文件
    uploadRemove(file, list) {
      this.fileList = list;
    },
    // 检查form 内容合规
    checkEdit() {
      this.$refs.editquestion.validate((valid) => {
        let checkform = true;
        if (valid) {
          if (
            this.form.type === "RADIO_QUESTION" ||
            this.form.type === "MULTI_SELECT_QUESTION"
          ) {
            if (
              this.form.selectionList instanceof Array &&
              this.form.selectionList.length < 4
            ) {
              checkform = false;
              this.$message.error("请至少输入四个选项");
            }
            const selectmap = this.form.selectionList.map((value) => value);
            const selectSet = new Set(selectmap);
            if (selectSet.size != this.form.selectionList.length) {
              checkform = false;
              this.$message.error("选项不能重复");
            }
            if (this.form.answer === "" || this.form.answer.length <= 0) {
              checkform = false;
              this.$message.error("请选择答案");
            }
          } else {
            if (this.form.answer === "") {
              checkform = false;
              this.$message.error("请输入答案");
            }
          }
        }
        if (valid && checkform) {
          this.saveEdit();
        }
      });
    },
    // 保存编辑
    saveEdit() {
      let formData = new FormData();
      const form = this.form;

      formData.append("fkCourseName", form.fkCourseName);
      formData.append("type", form.type);
      formData.append("score", form.score);
      formData.append("titleDetail", form.titleDetail);
      formData.append("remarks", form.remarks);
      if (form.id !== null || form.id !== undefined) {
        formData.append("id", form.id);
      }
      if (form.selectionList instanceof Array && form.selectionList.length > 0) {
        formData.append("selectionList", JSON.stringify(form.selectionList));
      } else {
        formData.append("selectionList", null);
      }
      if (form.answer instanceof Array && form.answer.length > 0) {
        formData.append("answer", JSON.stringify(form.answer));
      } else {
        formData.append("answer", form.answer);
      }

      let oldimgs = new Array();
      for (let i = 0; i < this.fileList.length; i++) {
        const element = this.fileList[i];
        if (element.status === "ready") {
          formData.append("files", element.raw);
        } else {
          oldimgs.push({
            name: element.name,
            url: element.url,
          });
        }
      }
      formData.append("imgList", JSON.stringify(oldimgs));

      this.$post("/question/insertorupdate", formData).then((res) => {
        if (res.code === 0) {
          this.$message.success("保存成功");
          _this.$emit("closeandreload");
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 删除选项
    removeSelect(index) {
      if (index !== -1) {
        this.form.selectionList.splice(index, 1);
      }
    },
    // 增加选项
    addSelect() {
      this.form.selectionList.push("");
    },
    // 删除所有选项
    removeAllSelect() {
      this.form.selectionList = [];
    },
  },
  created() {
    _this = this;
  },
  mounted() {},
};
</script>
<style>
.el-input {
  font-size: 15px;
}
.answerlist .el-tag--info {
  max-width: 98%;
}
.el-select-dropdown {
  max-width: 28%;
}
.answerlist .el-select__tags-text {
  display: inline-block;
  width: 98%;
  overflow: hidden;
  text-overflow: ellipsis;
}
.el-select .el-tag__close.el-icon-close {
  top: -5px;
  right: 5px;
}
.questionupload {
  width: 60%;
}
div.el-upload.el-upload--picture {
  height: 40px;
  width: 80px;
}
div.el-upload__tip {
  margin-top: 0px;
}
/* 谷歌 */
/deep/input::-webkit-outer-spin-button,
/deep/input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
}
/* 火狐 */
/deep/input {
  -moz-appearance: textfield;
}
</style>
